<template>
  <div>
    <!-- 卡片一 -->
    <el-card style="height: 70px">
      <el-form :inline="true" class="headerForm">
        <el-form-item label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            v-has="`btn.User.add`"
            icon="Search"
          >
            搜索
          </el-button>
          <el-button icon="RefreshRight" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 卡片二 -->
    <el-card style="margin-top: 20px">
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <el-button
        type="danger"
        @click="deleteSelectedRole"
        :disabled="selectedRoleArr.length > 0 ? false : true"
      >
        批量删除
      </el-button>
      <!-- 展示用户信息的表格 -->
      <el-table
        border
        style="margin: 20px 0"
        :data="RoleArr"
        @selection-change="selectedChange"
      >
        <el-table-column align=" center" type="selection"></el-table-column>

        <el-table-column
          type="index"
          header-align="center"
          align="center"
          width="100"
          label="序号"
        >
          <template #default="scope">
            <span>{{ (current - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="角色名称"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="角色标识"
          prop="role"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="操作" width="300px">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setPermission(row)"
            >
              权限分配
            </el-button>

            <el-button
              size="small"
              type="primary"
              icon="Edit"
              @click="edit(row)"
            >
              编辑
            </el-button>
            <el-popconfirm title="确定删除该角色?" @confirm="deleteRole(row)">
              <template #reference>
                <el-button size="small" type="primary" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        :page-sizes="[1, 5, 10, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 添加和修改用户的抽屉组件 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4 style="font-weight: bold; color: black">
          {{ form.id ? ' 修改角色' : '添加角色' }}
        </h4>
      </template>
      <template #default>
        <el-form :model="form" ref="formRef">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="form.roleName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色标识" :label-width="formLabelWidth">
            <el-input v-model="form.role" autocomplete="off" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 分配权限的抽屉组件 -->
    <el-drawer v-model="drawer1" @close="closeDrawer">
      <template #header>
        <h4>权限分配</h4>
      </template>
      <template #default>
        <!-- 树形控件 -->
        <el-tree
          ref="tree"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectedArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="finallySave">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqDelete,
  reqList,
  reqAdd,
  reqUpdate,
  reqDeleteBatch,
  reqGetRoleMenu,
  reqSavePermission,
} from '@/api/mis/role/index'
import { ElMessage, ElDrawer, ElMessageBox } from 'element-plus'
import type { Role, MenuData } from '@/api/mis/role/type'
let current = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(10)
// 存储获取到的已有的信息
let RoleArr = ref<Role[]>()

// 存储搜索关键字
let roleName = ref<string>('')

//用于控制添加修改用户抽屉的显示和隐藏
let drawer = ref<boolean>(false)
// 控制分配权限的抽屉
const drawer1 = ref<boolean>(false)
const formLabelWidth = '80px'
// 存储获取到的所有菜单信息
const menuArr = ref<MenuData[]>()
// 定义一个选中菜单的数据
const selectedArr = ref([])

// 获取树形控件
const tree = ref()

//用于新增或修改所用的表单
const form = reactive({
  roleName: '',
  role: '',
  id: 0,
})
// 树形控件相关设置
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 获取抽屉组件中的表单对象
const formRef = ref()
let selectedRoleArr = ref([])

// // 获取抽屉组件中的表单对象
// 挂载完成之后获取所有留言信息
onMounted(() => {
  getAllRole()
})
// 获取所有用户信息的方法
const getAllRole = async () => {
  const params = {
    current: current.value,
    pageSize: pageSize.value,
    roleName: roleName.value,
  }
  const result = await reqList(params)
  if (result.code === '0') {
    RoleArr.value = result.data.records
    total.value = result.data.total ?? 0 // 如果 total 是 undefined，则使用 0 作为默认值
  }
}
// 当前页改变时的回调
const handleCurrentChange = () => {
  getAllRole()
}
// 每页数据条数变化时的回调
const handleSizeChange = () => {
  current.value = 1
  getAllRole()
}
// 搜索按钮的回调
const search = () => {
  getAllRole()
}
const addRole = () => {
  drawer.value = true
  // 清空数据
  Object.assign(form, {
    roleName: '',
    role: '',
  })
  form.id = 0
  nextTick(() => {
    formRef.value.resetFields()
  })
}

const deleteRole = async (row: any) => {
  const params = {
    id: row.id,
  }
  const result = await reqDelete(params)
  if (result.code == 0) {
    ElMessage({ type: 'success', message: '删除成功！' })
    getAllRole()
  } else {
    ElMessage({ type: 'error', message: '删除失败！' })
  }
}
const edit = async (row: any) => {
  drawer.value = true
  //将row对象中的树形复制到form中
  Object.assign(form, row)
}
// // 重置按钮的回调
const reset = () => {
  roleName.value = ''
  getAllRole()
}
// 保存按钮的回调
const save = async () => {
  let result: any
  if (form.id == 0) {
    result = await reqAdd(form)
  } else {
    result = await reqUpdate(form)
  }
  if (result.code == 0) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: form.id ? ' 修改成功' : '添加成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: result.message,
    })
  }
  getAllRole()
}
// 取消按钮的回调
const cancel = () => {
  drawer1.value = false
  menuArr.value = []
  selectedArr.value = []
}

// 表单项被改变选中状态时会触发的回调
const selectedChange = (value: any) => {
  selectedRoleArr.value = value
}
// 批量删除按钮的回调
const deleteSelectedRole = async () => {
  const idList = selectedRoleArr.value.map((item: any) => {
    return item.id
  })

  const result = await reqDeleteBatch(idList)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功！' })
    getAllRole()
  } else {
    ElMessage({ type: 'error', message: '删除失败！' })
  }
}

// 分配权限按钮的回调
const setPermission = async (row: any) => {
  Object.assign(form, row)
  drawer1.value = true
  const result = await reqGetRoleMenu(form.id)
  if (result.code === '0') {
    menuArr.value = result.data
    selectedArr.value = filterSelectedArr(menuArr.value, [])
    console.log(selectedArr.value)
  }
}

// 过滤被选中id[3即菜单才过滤]的菜单项的方法
const filterSelectedArr = (allMenu: any, initArr: any) => {
  allMenu.forEach((item: any) => {
    if (item.children && item.children.length > 0) {
      filterSelectedArr(item.children, initArr)
    }
    if (item.children == null && item.selected) {
      initArr.push(item.id)
    }
    if (item.selected && item.level === 3) {
      initArr.push(item.id)
    }
  })
  return initArr
}

// 分配权限最后确定按钮的回调
const finallySave = async () => {
  // 选中权限的id
  const arr1 = tree.value.getCheckedKeys()
  // 半选的id
  const arr2 = tree.value.getHalfCheckedKeys()
  // 合并成一个新数组
  const permissionId = arr1.concat(arr2)
  const params = {
    roleId: form.id,
    permissionIds: permissionId,
  }
  const result = await reqSavePermission(params)
  if (result.code == 0) {
    ElMessage({ type: 'success', message: '分配成功' })
  } else {
    ElMessage({ type: 'error', message: '分配失败' })
  }
  drawer1.value = false
  form.id = 0
}

// 关闭抽屉并清空数据函数
const closeDrawer = () => {
  drawer1.value = false
  menuArr.value = [] // 清空菜单数据
  selectedArr.value = [] // 清空选中数据
}
</script>

<style scoped>
.headerForm {
  display: flex;
  justify-content: space-between;
}
</style>
